from information import constants
from information.models import User, News, Category
from information.utils.response_code import RET
from . import index_blu
from flask import render_template, session, current_app, request, jsonify


@index_blu.route('/')
def hello_world():
    #  显示用户登录
    user_id = session.get("user_id")
    user = None
    try:
        if user_id:
            user = User.query.get(user_id)  # type: User

    except Exception as e:
        current_app.logger.error(e)
    # 右边的排行
    new_list = []
    try:
        new_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    news = []
    for new in new_list:
        news.append(new.to_basic_dict())
    # 查询分类数据,通过模板的形式渲染出来
    categories = Category.query.all()
    category_li = []
    for category in categories:
        category_li.append(category.to_dict())
    data = {
        "user_info": user.to_dict() if user else None,
        "news_dict_li": news,
        "category_li": category_li
    }

    return render_template("news/index.html", data=data)


@index_blu.route("/favicon.ico")
def favicon_ico():
    from flask import current_app
    return current_app.send_static_file("news/favicon.ico")


@index_blu.route("/news_list")
def news_list():
    """
       获取指定分类的新闻列表
       1. 获取参数
       2. 校验参数
       3. 查询数据
       4. 返回数据
       :return:
       """
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")

    # 2. 校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数不正确")
    # 如果cid不等于1，说明是查找指定分类
    filters = []
    if cid != 1:
        filters.append(News.category_id == cid)
    # 查询数据库，按照指定filters
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()) \
            .paginate(page, per_page, False)
        news_list = paginate.items
        total_page = paginate.pages
        current_page = paginate.page

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")


# 构造新闻列表的字典数据
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_dict())
    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_dict_li": news_dict_li
    }
        # 返回数据
    return jsonify(errno=RET.OK, errmsg="OK", data=data)
